#!/bin/bash

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

print_info() { echo -e "${BLUE}ℹ${NC} $1"; }
print_success() { echo -e "${GREEN}✓${NC} $1"; }
print_warning() { echo -e "${YELLOW}⚠${NC} $1"; }
print_error() { echo -e "${RED}✗${NC} $1"; }

# 检测操作系统和架构
OS=$(uname -s | tr '[:upper:]' '[:lower:]')
ARCH=$(uname -m)

case $ARCH in
    x86_64) ARCH="amd64" ;;
    aarch64|arm64) ARCH="arm64" ;;
    *)
        print_error "不支持的架构: $ARCH"
        exit 1
        ;;
esac

case $OS in
    linux) OS="linux" ;;
    darwin) OS="darwin" ;;
    *)
        print_error "不支持的操作系统: $OS"
        print_info "请手动下载适合您系统的版本"
        exit 1
        ;;
esac

# 获取最新版本
print_info "检测最新版本..."
LATEST_VERSION=$(curl -s https://api.github.com/repos/yourusername/kscan/releases/latest | grep '"tag_name":' | sed -E 's/.*"v([^"]+)".*/\1/')

if [ -z "$LATEST_VERSION" ]; then
    print_error "无法获取最新版本信息"
    exit 1
fi

print_success "最新版本: v$LATEST_VERSION"

# 构建下载 URL
BINARY_NAME="kscan-${LATEST_VERSION}-${OS}-${ARCH}"
ARCHIVE_NAME="${BINARY_NAME}.tar.gz"
DOWNLOAD_URL="https://github.com/yourusername/kscan/releases/download/v${LATEST_VERSION}/${ARCHIVE_NAME}"

print_info "系统信息: ${OS}/${ARCH}"
print_info "准备下载: ${ARCHIVE_NAME}"

# 创建临时目录
TMP_DIR=$(mktemp -d)
cd "$TMP_DIR"

# 下载文件
print_info "正在下载..."
if ! curl -L -o "$ARCHIVE_NAME" "$DOWNLOAD_URL" 2>/dev/null; then
    print_error "下载失败"
    print_info "请手动从以下地址下载: $DOWNLOAD_URL"
    rm -rf "$TMP_DIR"
    exit 1
fi

print_success "下载完成"

# 下载校验和
print_info "验证文件完整性..."
if curl -L -o "${ARCHIVE_NAME}.sha256" "${DOWNLOAD_URL}.sha256" 2>/dev/null; then
    if command -v sha256sum >/dev/null 2>&1; then
        if sha256sum -c "${ARCHIVE_NAME}.sha256" >/dev/null 2>&1; then
            print_success "文件校验成功"
        else
            print_warning "文件校验失败，但继续安装"
        fi
    fi
fi

# 解压
print_info "正在解压..."
tar -xzf "$ARCHIVE_NAME"
print_success "解压完成"

# 安装
INSTALL_DIR="/usr/local/bin"
if [ -w "$INSTALL_DIR" ]; then
    print_info "安装到 $INSTALL_DIR..."
    mv "$BINARY_NAME" "$INSTALL_DIR/kscan"
    chmod +x "$INSTALL_DIR/kscan"
    print_success "安装成功！"
else
    print_warning "没有 $INSTALL_DIR 的写权限"
    print_info "尝试使用 sudo 安装..."
    sudo mv "$BINARY_NAME" "$INSTALL_DIR/kscan"
    sudo chmod +x "$INSTALL_DIR/kscan"
    print_success "安装成功！"
fi

# 清理
cd - >/dev/null
rm -rf "$TMP_DIR"

# 验证安装
print_info "验证安装..."
if command -v kscan >/dev/null 2>&1; then
    INSTALLED_VERSION=$(kscan --version 2>&1 | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' || echo "unknown")
    print_success "KSCAN 已成功安装！"
    echo
    echo "安装位置: $INSTALL_DIR/kscan"
    echo "版本: v$INSTALLED_VERSION"
    echo
    print_info "运行 'kscan --help' 查看使用帮助"
else
    print_error "安装可能失败，请检查"
    exit 1
fi